import 'package:flutter/widgets.dart';
import 'package:heytea_kit/lifecycle/stoppable_service.dart';
import 'package:heytea_kit/logger.dart';

class LifecycleManager extends StatefulWidget {
  final Widget child;
  LifecycleManager({Key key, this.child}) : super(key: key);
  _LifecycleManagerState createState() => _LifecycleManagerState();
}

class _LifecycleManagerState extends State<LifecycleManager>
    with WidgetsBindingObserver {
  List<StoppableService> services = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: widget.child,
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    HeyTeaLogger().v('$this, state = $state');
    services.forEach((service) {
      switch (state) {
        case AppLifecycleState.resumed:
          service.start();
          break;
        case AppLifecycleState.paused:
          service.stop();
          break;
        default:
          break;
      }
    });
  }
}
